const axios = require('axios')
const qs = require('querystring')
const result = require('./handle.js')

// 获取tokenurl的地址
let param = qs.stringify({
	grant_type: 'client_credential',
	appid: 'wxa7aef961cc16274b',
	secret: '2933502a3e11860c2ffd7215b5adbd0b'
})

let url = 'https://api.weixin.qq.com/cgi-bin/token?' + param
// 云环境id
let env = 'htzz-english-7g42yzwx555b483a'
//添加数据url
let addUrl = 'https://api.weixin.qq.com/tcb/databaseadd?access_token='
//查询数据url
let tripUrl = 'https://api.weixin.qq.com/tcb/databasequery?access_token='
class getToken {
	constructor(arg) {}
	async gettoken() {
		try {
			let token = await axios.get(url)
			if (token.status == 200) {
				return token.data.access_token
			} else {
				throw '获取token错误'
			}
		} catch (e) {
			//TODO handle the exception
			throw new result(e, 500)
		}
	}
	async posteve(dataurl, query) {
		try {
			let token = await this.gettoken()
			let data = await axios.post(dataurl + token, {
				env,
				query
			})
			// console.log(data)
			if (data.data.errcode == 0) {
				// 执行成功 返回数据
				return data.data

			} else {
				// 查询失败
				throw '请求错误'

			}
		} catch (e) {
			//TODO handle the exception
			throw new result(e, 500)
		}

	}


}
module.exports = {
	getToken,
	addUrl,
	tripUrl

}
